package org.jim.server.command.handler;

import org.jim.core.ImChannelContext;
import org.jim.core.ImConst;
import org.jim.core.ImPacket;
import org.jim.core.exception.ImException;
import org.jim.core.packets.ChatBody;
import org.jim.core.packets.Command;
import org.jim.core.packets.EditBody;
import org.jim.core.packets.RespBody;
import org.jim.core.utils.JsonKit;
import org.jim.server.ImServerChannelContext;
import org.jim.server.JimServerAPI;
import org.jim.server.command.AbstractCmdHandler;
import org.jim.server.util.ChatKit;

import java.io.UnsupportedEncodingException;

public class EditReqHandler extends AbstractCmdHandler {
    @Override
    public Command command() {
        return Command.COMMAND_EDIT_RESP;
    }

    @Override
    public ImPacket handler(ImPacket imPacket, ImChannelContext imChannelContext) throws ImException {

        if (imPacket.getBody() == null) {
            throw new ImException("body is null");
        }
        try {
            String text = new String(imPacket.getBody(), ImConst.CHARSET);
            EditBody body = JsonKit.toBean(text,EditBody.class);
            if(body != null){
                body.setUserId(imChannelContext.getUserId());
                ImPacket chatPacket = new ImPacket(Command.COMMAND_EDIT_RESP,new RespBody(Command.COMMAND_EDIT_RESP,body).toByte());
                JimServerAPI.sendToUser(body.getToUserId(), chatPacket);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
